<template>
  <div class="test-api">
    <h1>API测试页面</h1>
    <el-card class="test-section">
      <template #header>
        <h3>Mock服务状态</h3>
      </template>
      <div class="status-info">
        <el-tag :type="useMockService ? 'success' : 'info'">
          Mock服务: {{ useMockService ? '启用' : '禁用' }}
        </el-tag>
        <el-tag type="info">
          API Base URL: {{ apiBaseURL }}
        </el-tag>
      </div>
    </el-card>

    <el-card class="test-section">
      <template #header>
        <h3>租户管理API测试</h3>
      </template>
      <div class="test-buttons">
        <el-button type="primary" @click="testGetTenants" :loading="loadingTenants">
          获取租户列表
        </el-button>
        <el-button type="success" @click="testCreateTenant" :loading="creatingTenant">
          创建租户
        </el-button>
        <el-button @click="testTenantStatistics" :loading="loadingStats">
          租户统计
        </el-button>
      </div>
      <div v-if="tenantResult" class="result-display">
        <h4>测试结果:</h4>
        <pre>{{ JSON.stringify(tenantResult, null, 2) }}</pre>
      </div>
    </el-card>

    <el-card class="test-section">
      <template #header>
        <h3>用户管理API测试</h3>
      </template>
      <div class="test-buttons">
        <el-button type="primary" @click="testGetUsers" :loading="loadingUsers">
          获取用户列表
        </el-button>
        <el-button type="success" @click="testCreateUser" :loading="creatingUser">
          创建用户
        </el-button>
        <el-button @click="testUserStatistics" :loading="loadingUserStats">
          用户统计
        </el-button>
      </div>
      <div v-if="userResult" class="result-display">
        <h4>测试结果:</h4>
        <pre>{{ JSON.stringify(userResult, null, 2) }}</pre>
      </div>
    </el-card>

    <el-card class="test-section">
      <template #header>
        <h3>权限管理测试</h3>
      </template>
      <div class="test-buttons">
        <el-button type="primary" @click="testGetRoles" :loading="loadingRoles">
          获取角色列表
        </el-button>
        <el-button @click="testGetPermissions" :loading="loadingPermissions">
          获取权限列表
        </el-button>
      </div>
      <div v-if="permissionResult" class="result-display">
        <h4>测试结果:</h4>
        <pre>{{ JSON.stringify(permissionResult, null, 2) }}</pre>
      </div>
    </el-card>

    <el-card class="test-section">
      <template #header>
        <h3>错误处理测试</h3>
      </template>
      <div class="test-buttons">
        <el-button type="danger" @click="testError">
          触发错误
        </el-button>
        <el-button type="warning" @click="testPermissionDenied">
          权限不足测试
        </el-button>
      </div>
      <div v-if="errorResult" class="result-display error">
        <h4>错误信息:</h4>
        <pre>{{ errorResult }}</pre>
      </div>
    </el-card>

    <el-card class="test-section">
      <template #header>
        <h3>集成测试</h3>
      </template>
      <div class="test-buttons">
        <el-button type="success" @click="runIntegrationTest" :loading="runningIntegrationTest">
          运行完整集成测试
        </el-button>
      </div>
      <div v-if="integrationTestResult" class="result-display">
        <h4>集成测试结果:</h4>
        <pre>{{ integrationTestResult }}</pre>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { tenantService } from '@/services/tenant.service'
import { userService } from '@/services/user.service'
import { permissionService } from '@/services/permission.service'
import { useMockService } from '@/services/mock.service'
import MockService from '@/services/mock.service'
import { runAllTests } from '@/utils/integration-test'

// 状态变量
const loadingTenants = ref(false)
const loadingUsers = ref(false)
const loadingStats = ref(false)
const loadingUserStats = ref(false)
const creatingTenant = ref(false)
const creatingUser = ref(false)
const loadingRoles = ref(false)
const loadingPermissions = ref(false)
const runningIntegrationTest = ref(false)

// 结果变量
const tenantResult = ref(null)
const userResult = ref(null)
const permissionResult = ref(null)
const errorResult = ref('')
const integrationTestResult = ref('')

// 配置信息
const apiBaseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api'

// 租户管理测试
const testGetTenants = async () => {
  loadingTenants.value = true
  try {
    const result = await tenantService.getTenants({
      skipCount: 0,
      maxResultCount: 10
    })
    tenantResult.value = result
    ElMessage.success(`成功获取 ${result.totalCount} 个租户`)
  } catch (error: any) {
    errorResult.value = error.message || '获取租户列表失败'
    ElMessage.error('获取租户列表失败')
  } finally {
    loadingTenants.value = false
  }
}

const testCreateTenant = async () => {
  creatingTenant.value = true
  try {
    const result = await tenantService.createTenant({
      name: '测试租户-' + Date.now(),
      code: 'TEST-' + Math.random().toString(36).substr(2, 5).toUpperCase(),
      adminEmailAddress: 'admin@test.com',
      adminPassword: 'Test123456!',
      databaseType: 'PostgreSQL',
      connectionString: 'Server=localhost;Port=5432;Database=test_db;'
    })
    tenantResult.value = result
    ElMessage.success('租户创建成功')
  } catch (error: any) {
    errorResult.value = error.message || '创建租户失败'
    ElMessage.error('创建租户失败')
  } finally {
    creatingTenant.value = false
  }
}

const testTenantStatistics = async () => {
  loadingStats.value = true
  try {
    const result = await tenantService.getTenantStatistics()
    tenantResult.value = result
    ElMessage.success('获取租户统计成功')
  } catch (error: any) {
    errorResult.value = error.message || '获取租户统计失败'
    ElMessage.error('获取租户统计失败')
  } finally {
    loadingStats.value = false
  }
}

// 用户管理测试
const testGetUsers = async () => {
  loadingUsers.value = true
  try {
    const result = await userService.getUsers({
      skipCount: 0,
      maxResultCount: 10
    })
    userResult.value = result
    ElMessage.success(`成功获取 ${result.totalCount} 个用户`)
  } catch (error: any) {
    errorResult.value = error.message || '获取用户列表失败'
    ElMessage.error('获取用户列表失败')
  } finally {
    loadingUsers.value = false
  }
}

const testCreateUser = async () => {
  creatingUser.value = true
  try {
    const result = await userService.createUser({
      userName: 'testuser-' + Date.now(),
      email: 'test@example.com',
      name: '测试',
      surname: '用户',
      password: 'Test123456!',
      roleNames: ['User']
    })
    userResult.value = result
    ElMessage.success('用户创建成功')
  } catch (error: any) {
    errorResult.value = error.message || '创建用户失败'
    ElMessage.error('创建用户失败')
  } finally {
    creatingUser.value = false
  }
}

const testUserStatistics = async () => {
  loadingUserStats.value = true
  try {
    const result = await userService.getUserStatistics()
    userResult.value = result
    ElMessage.success('获取用户统计成功')
  } catch (error: any) {
    errorResult.value = error.message || '获取用户统计失败'
    ElMessage.error('获取用户统计失败')
  } finally {
    loadingUserStats.value = false
  }
}

// 权限管理测试
const testGetRoles = async () => {
  loadingRoles.value = true
  try {
    const result = await permissionService.getRoles({
      skipCount: 0,
      maxResultCount: 10
    })
    permissionResult.value = result
    ElMessage.success(`成功获取 ${result.totalCount} 个角色`)
  } catch (error: any) {
    errorResult.value = error.message || '获取角色列表失败'
    ElMessage.error('获取角色列表失败')
  } finally {
    loadingRoles.value = false
  }
}

const testGetPermissions = async () => {
  loadingPermissions.value = true
  try {
    const result = await permissionService.getAllPermissions()
    permissionResult.value = { items: result, totalCount: result.length }
    ElMessage.success(`成功获取 ${result.length} 个权限`)
  } catch (error: any) {
    errorResult.value = error.message || '获取权限列表失败'
    ElMessage.error('获取权限列表失败')
  } finally {
    loadingPermissions.value = false
  }
}

// 错误测试
const testError = async () => {
  try {
    // 故意触发一个错误
    await MockService.bulkOperation({
      operation: 'INVALID_OPERATION',
      itemIds: ['invalid-id']
    })
  } catch (error: any) {
    errorResult.value = error.message || '测试错误'
    ElMessage.error('测试错误处理成功')
  }
}

const testPermissionDenied = async () => {
  try {
    // 模拟权限不足的情况
    throw new Error('权限不足：没有执行此操作的权限')
  } catch (error: any) {
    errorResult.value = error.message || '权限测试'
    ElMessage.warning('权限测试成功')
  }
}

// 集成测试
const runIntegrationTest = async () => {
  runningIntegrationTest.value = true
  try {
    console.log('开始运行集成测试...')
    const results = await runAllTests()

    const passedTests = Object.values(results).filter(Boolean).length
    const totalTests = Object.keys(results).length

    integrationTestResult.value = `测试完成！

总测试数: ${totalTests}
通过测试: ${passedTests}
失败测试: ${totalTests - passedTests}

详细结果:
- 租户管理服务: ${results.tenant ? '✅ 通过' : '❌ 失败'}
- 用户管理服务: ${results.user ? '✅ 通过' : '❌ 失败'}
- 权限管理服务: ${results.permission ? '✅ 通过' : '❌ 失败'}

${passedTests === totalTests ? '🎉 所有测试通过！前端服务集成成功！' : '⚠️ 部分测试失败，请检查相关服务实现'}
`

    if (passedTests === totalTests) {
      ElMessage.success('集成测试全部通过！')
    } else {
      ElMessage.warning(`集成测试部分失败，通过率: ${passedTests}/${totalTests}`)
    }
  } catch (error: any) {
    integrationTestResult.value = `集成测试执行失败: ${error.message || error}`
    ElMessage.error('集成测试执行失败')
  } finally {
    runningIntegrationTest.value = false
  }
}
</script>

<style scoped>
.test-api {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-section {
  margin-bottom: 20px;
}

.test-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.status-info {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.result-display {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  margin-top: 16px;
}

.result-display pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 400px;
  overflow-y: auto;
}

.result-display.error pre {
  color: #f56c6c;
}

h1 {
  margin-bottom: 30px;
  color: #303133;
}

h3 {
  margin: 0;
  color: #303133;
}

h4 {
  margin: 0 0 12px 0;
  color: #606266;
}
</style>